package com.tuocent.dagv2.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.entity.Transfer;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.constant.PublicConst;
import com.tuocent.dagv2.entity.*;
import com.tuocent.dagv2.mapper.TaskWorkProcedureMapper;
import com.tuocent.dagv2.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.ui.Model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-07-31
 */
@Service
public class TaskWorkProcedureServiceImpl extends ServiceImpl<TaskWorkProcedureMapper, TaskWorkProcedure> implements ITaskWorkProcedureService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private SnowFlakeID snowFlakeID;
    @Autowired
    private IWorkProceduresService workProceduresService;
    @Autowired
    private IUserPermissionService userPermissionService;
    @Autowired
    private IProjectsService projectsService;
    @Autowired
    private IUsersService usersService;

    @Override
    public String setTaskWorkProcedure(Model model, String id, String pid) {
        model.addAttribute("tid", id);
        model.addAttribute("pid", pid);
        return "/project/setTaskWorkProcedure";
    }

    @Override
    public AjaxResult getTaskWorkProcedure(String tid, String pid) {

        List<WorkProcedures> workProcedures = workProceduresService.list(new QueryWrapper<WorkProcedures>()
                .eq("sys", "0")
                .orderByAsc("id"));
        List<TaskWorkProcedure> taskWorkProcedures = list(new QueryWrapper<TaskWorkProcedure>()
                .select("work_id")
                .eq("pid", pid)
                .eq("tid", tid));
        List<Transfer> transfers = new ArrayList<>();
        List<String> values = new ArrayList<>();
        for (WorkProcedures work : workProcedures) {
            Transfer transfer = new Transfer();
            transfer.setValue(work.getId().toString());
            transfer.setTitle(work.getWorkname());
            transfer.setChecked("");
            transfer.setDisabled("");
            transfers.add(transfer);
        }
        for (TaskWorkProcedure taskWork : taskWorkProcedures) {
            values.add(taskWork.getWorkId().toString());
        }
        List<Object> data = new ArrayList<>();
        data.add(transfers);
        data.add(values);
        return AjaxResult.success(data);

    }

    @Override
    public AjaxResult saveTaskWorkProcedure(JSONObject data) {
        String pid = data.containsKey("pid") ? data.get("pid").toString() : "";
        String tid = data.containsKey("tid") ? data.get("tid").toString() : "";
        String action = data.containsKey("action") ? data.get("action").toString() : "0";
        JSONArray dataArray = data.getJSONArray("data");
        List<Transfer> transfers = JSON.parseArray(dataArray.toJSONString(), Transfer.class);

        DataSourceTransactionManager tran = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus update = tran.getTransaction(def);

        switch (action) {
            case "0":
                for (Transfer transfer : transfers) {
                    if (count(new QueryWrapper<TaskWorkProcedure>()
                            .eq("pid", pid)
                            .eq("tid", tid)
                            .eq("work_id", transfer.getValue())) == 0) {
                        TaskWorkProcedure work = new TaskWorkProcedure();
                        work.setId(snowFlakeID.getId());
                        work.setPid(pid);
                        work.setTid(tid);
                        work.setWorkId(Integer.valueOf(transfer.getValue()));
                        work.setWorkName(transfer.getTitle());
                        work.setIdx(work.getWorkId());
                        work.setSys("0");
                        save(work);
                    }
                }
                break;
            case "1":
                for (Transfer transfer : transfers) {
                    remove(new QueryWrapper<TaskWorkProcedure>().eq("pid", pid).eq("tid", tid).eq("work_id", transfer.getValue()));
                }
                break;
        }
        try {
            tran.commit(update);
            return AjaxResult.success("设置流程工序成功");
        } catch (Exception e) {
            tran.rollback(update);
            return AjaxResult.error("设置流程工序失败，错误信息：" + e.getMessage());
        }
    }

    @Override
    public String setUserWorkProcedure(Model model, String userId) {
        model.addAttribute("userId", userId);
        //查找用户信息
        Users user = usersService.getById(userId);
        if (user == null) {
            model.addAttribute("message", "没有找到该用户的信息");
            return "/home/error";
        }
        if (user.getIsSys().equals("1")) {
            model.addAttribute("message", "该用户为系统用户，不可设置此功能");
            return "/home/error";
        }

        List<Projects> projectsList = projectsService.list(new QueryWrapper<Projects>().eq("is_del", "0"));
        model.addAttribute("projectsList", projectsList);
        return "/project/setUserWorkProcedure";
    }

    @Override
    public AjaxResult getUserWorkProcedure(String tid, String pid, String userId) {
        List<TaskWorkProcedure> workProcedures = list(new QueryWrapper<TaskWorkProcedure>()
                .eq("pid", pid)
                .eq("tid", tid)
                .orderByAsc("id"));
        List<UserPermission> userPermissions = userPermissionService.list(new QueryWrapper<UserPermission>()
                .eq("pid", pid)
                .eq("tid", tid)
                .eq("userid", userId));
        List<Object> data = getWorkProcedures(workProcedures, userPermissions);
        return AjaxResult.success(data);
    }

    @Override
    public AjaxResult saveUserWorkProcedure(JSONObject data) {
        String pid = data.containsKey("pid") ? data.get("pid").toString() : "";
        String tid = data.containsKey("tid") ? data.get("tid").toString() : "";
        String userId = data.containsKey("userId") ? data.get("userId").toString() : "";
        String action = data.containsKey("action") ? data.get("action").toString() : "0";
        JSONArray dataArray = data.getJSONArray("data");
        List<Transfer> transfers = JSON.parseArray(dataArray.toJSONString(), Transfer.class);
        //查找用户信息
        Users user = usersService.getById(userId);
        if (user == null) {
            return AjaxResult.success("没有找到该用户的信息");
        }

        /*
        if (user.getRoleId().equals(PublicConst.USER_ROLE_ID)) {
            for (Transfer transfer : transfers) {
                System.err.println(transfer.getValue());
                if (!Arrays.asList("2", "18").contains(transfer.getValue())) {
                    return CommonResult.failed("该用户角色没有" + transfer.getTitle() + "的权限");
                }
            }
        }

         */

        DataSourceTransactionManager tran = new DataSourceTransactionManager(jdbcTemplate.getDataSource());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus update = tran.getTransaction(def);

        switch (action) {
            case "0":
                for (Transfer transfer : transfers) {
                    if (userPermissionService.count(new QueryWrapper<UserPermission>()
                            .eq("pid", pid)
                            .eq("tid", tid)
                            .eq("userId", userId)
                            .eq("keyid", transfer.getValue())) == 0) {
                        UserPermission work = new UserPermission();
                        work.setId(snowFlakeID.getId());
                        work.setPid(pid);
                        work.setTid(tid);
                        work.setUserid(userId);
                        work.setKeyid(transfer.getValue());
                        work.setModel(12);
                        work.setIsuse("1");
                        userPermissionService.save(work);
                    }
                }
                break;
            case "1":
                for (Transfer transfer : transfers) {
                    userPermissionService.remove(new QueryWrapper<UserPermission>()
                            .eq("pid", pid)
                            .eq("tid", tid)
                            .eq("userid", userId)
                            .eq("keyid", transfer.getValue())
                            .eq("model", 12));
                }
                break;
        }
        try {
            tran.commit(update);
            return AjaxResult.success("设置用户工序成功");
        } catch (Throwable e) {
            tran.rollback(update);
            log.error(e.getMessage());
            return AjaxResult.error("设置用户工序，错误信息：" + e.getMessage());
        }
    }

    private List<Object> getWorkProcedures(List<TaskWorkProcedure> workProcedures, List<UserPermission> userPermissions) {
        List<Transfer> transfers = new ArrayList<>();
        List<String> values = new ArrayList<>();
        for (TaskWorkProcedure work : workProcedures) {
            Transfer transfer = new Transfer();
            transfer.setValue(work.getWorkId().toString());
            transfer.setTitle(work.getWorkName());
            transfer.setChecked("");
            transfer.setDisabled("");
            transfers.add(transfer);
        }
        for (UserPermission userPermission : userPermissions) {
            values.add(userPermission.getKeyid());
        }
        List<Object> data = new ArrayList<>();
        data.add(transfers);
        data.add(values);
        return data;
    }


}
